/*
 *  Copyright (C) 2010 mathieu
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.boc.botv.web.controller;

import com.boc.botv.common.Database;
import com.boc.botv.model.Bet;
import com.boc.botv.model.BetChoice;
import com.boc.botv.service.BetManager;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 *
 * @author mathieu
 */
@Controller
@RequestMapping("/pari/")
public class BetController {

  @Autowired
  private BetManager manager;
  private Map<String, Object> map = new HashMap<String, Object>();

  public BetController() {
    map.put("menu", "home");
    map.put("path", "../");
    map.put("title", "Miser sur un pari");
  }

  @RequestMapping(value = "index", method = RequestMethod.GET)
  public String setUpBetForm(@RequestParam(value = "id", required = true) int betId, Model model) {
    Database.startTransaction(false);
    Bet bet = manager.getBet(betId);
    List<BetChoice> betChoicesList = manager.getChoices(betId);
    model.addAllAttributes(map);
    model.addAttribute("bet", bet);
    model.addAttribute("choices", betChoicesList);
    Database.closeTransaction();
    return "section/bet";
  }

  @RequestMapping(value = "index", method = RequestMethod.POST)
  public String processBetForm(
          @RequestParam(value = "choice", required = true) int choiceId,
          @RequestParam(value = "amount", required = true) double amount,
          @RequestParam(value = "betId", required = true) int betId,
          @RequestParam(value = "userId", required = true) int userId) {
    Database.startTransaction(false);
    if (amount <= 0) {
      Database.closeTransaction();
      return "redirect:/pari/index.htm?id=" + betId;
    }
    if (manager.addGamer(userId, choiceId, amount)) {
      Database.closeTransaction();
      return "redirect:/index.htm";
    }
    Database.closeTransaction();
    return "redirect:index.htm?id=" + betId;
  }
}
